import Button from "@/components/Button";
import CircleButton from "@/components/CircleButton";
import EmojiList from "@/components/EmojiList";
import EmojiPicker from "@/components/EmojiPicker";
import EmojiSticker from "@/components/EmojiSticker";
import IconButton from "@/components/IconButton";
import ImageViewer from "@/components/ImageViewer";
import { ImageRef } from "expo-image";
import * as ImagePicker from "expo-image-picker";
import { usePermissions, saveToLibraryAsync } from "expo-media-library";
import { useRef, useState } from "react";
import { ImageSourcePropType, StyleSheet, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { captureRef } from "react-native-view-shot";
const placeholderImage = require('@/assets/images/background-image.png');

/**
 * expo的tab导航,貌似是必须要求以(tabs)命名文件夹
 * 
 * 
 */

export default function Index() {
  // 访问设备资源, 需要申请权限
  const [stauts, requestPermission] = usePermissions()

  // 创建一个imageRef的引用
  const screenshotRef = useRef(null)

  if (stauts === null) { // 如果没有权限, 弹出对应的权限申请框
    requestPermission()
  }

  // 使用useState hook来保存选中的图片, <string|undefined> 这个语法代表泛型,可接受的类型是string或undefined
  const [imageSelected, setImageSelected] = useState('');

  // defined a boolean state showAppOptions
  const [showAppOptions, setShowAppOptions] = useState<boolean>(false)

  // 定义emojiPicker是否可展示的状态
  const [isEmojiPickerVisible, setIsEmojiPickerVisible] = useState<boolean>(false)

  // 定义一个存储选中的emoji的变量
  const [pickedEmoji, setPickedEmoji] = useState<ImageSourcePropType | undefined>(undefined)



  const onModalClose = () => {
    setIsEmojiPickerVisible(false)
  }

  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      quality: 1,
    });
    console.log('curr picker resp: ', result)

    if (!result.assets || result.assets.length <= 0) {
      alert('you didn\'t select image');
      return false;
    }

    // 此时需要将选中的iamge通过prop传递给ImageViewer组件
    setImageSelected(result['assets'][0].uri)

    setShowAppOptions(true)

    console.log('now image', imageSelected)
  }

  // 保存图片到本地
  const onSaveImageAsync = async function () {
    try {
      // 创建截图
      const localuri = await captureRef(screenshotRef, {
        height: 440,
        quality: 1
      })

      await saveToLibraryAsync(localuri);

      if (localuri) {
        alert('保存成功')
      }
    } catch (e) {
      console.log('captrue screenshot fail , e: ', e)
    }
  }

  // 给选择的图片添加水印
  const onAddWaterImg = async function () {
    setIsEmojiPickerVisible(true)
  }

  /**
   * 撤销操作
   * 这里撤销的时候, 如何把原始的背景图也复原?? 估计是类似于jq选中这个元素, 替换图片的source??
   */
  const handleRefresh = function () {
    setPickedEmoji(undefined) // 撤销emoji
    setShowAppOptions(false) // 恢复初始页
    // setImageSelected(require('@/assets/images/background-image.png')) 
  }

  const afterSelected = (
    <View style={styels.optionContainer}>
      <View style={styels.optionRow}>
        <IconButton label="撤销" icon="refresh" color="lightgreen" onPress={handleRefresh} />
        <CircleButton onPress={() => {
          onAddWaterImg()
        }} />
        <IconButton label="保存" icon="save-alt" color="lightgreen" onPress={() => {
          onSaveImageAsync()
        }} />
      </View>
    </View>
  );
  const beforeSelected = (<View style={styels.footerContainer}>

    <Button label="选择一张照片" theme="primary" onPress={pickImageAsync}></Button>

    <Button label="使用这张图片" onPress={() => {
      setShowAppOptions(true)
      console.log('now showAppOtions: ', showAppOptions)
    }}></Button>
  </View>);




  return (
    <GestureHandlerRootView
      style={styels.container}
    >
      {/* 
        collapsable 这个值默认为true, 设置为false, 有特定含义 
        React Native 在渲染时会对一些不可见或纯容器性质的组件进行优化，将其从原生视图树中移除（但保留在 JS 层面）。
        这种优化称为 "折叠"（Collapsing）。当 collapsable={false} 时：
          强制该 View 渲染为原生视图，即使它没有自己的尺寸或样式。
          确保子组件的布局和测量正常工作，尤其是在需要精确计算位置或尺寸的场景中。
      */}
      <View ref={screenshotRef} collapsable={false} style={styels.imageContainer}>
        <ImageViewer source={placeholderImage} selectedImage={imageSelected} />
        {pickedEmoji && <EmojiSticker size={40} source={pickedEmoji} />}
      </View>
      {showAppOptions ? afterSelected : beforeSelected}
      <EmojiPicker isVisible={isEmojiPickerVisible} onClose={onModalClose}>
        {/* 为什么我这里, 选中贴纸之后不能自动关闭弹窗? */}
        <EmojiList onSelect={setPickedEmoji} onCloseModal={onModalClose} />
      </EmojiPicker>
    </GestureHandlerRootView  >
  );
}

const styels = StyleSheet.create({
  container: {
    backgroundColor: "#25292e",
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  optionContainer: {
    position: 'absolute',
    bottom: 60,
  },
  optionRow: {
    alignItems: 'center',
    flexDirection: 'row',
  },
  text: {
    color: "white"
  },
  button: {
    color: "lightblue",
    fontSize: 20,
    textDecorationLine: 'underline', // 给文字加上下划线
  },
  imageContainer: {
    flex: 1,
    paddingTop: 28
  },
  image: {
    width: 320,
    height: 440,
    borderRadius: 18,
  },
  footerContainer: {
    flex: 1 / 3, // todo 这特么是什么用法??
    alignItems: "center"
  }
})
